package org.hang.jvm.classfile;

import java.math.BigInteger;

/**
 * 说明
 *
 * @author 廖景航
 * @date created on 2022/3/10 下午4:47
 */
public class ClassReader {

    private byte[] data;
    private int cursorIndex = 0;

    public ClassReader(byte[] classData) {
        this.data = classData;
    }

    /**
     * u1， int 是4字节
     *
     * @return
     */
    public int readUint8() {
        byte[] val = readByte(1);
        return byte2int(val);
    }


    /**
     * u2
     *
     * @return
     */
    public int readUint16() {
        byte[] val = readByte(2);
        return byte2int(val);
    }

    /**
     * u4，long类型时8字节
     *
     * @return
     */
    public long readUint32() {
        byte[] val = readByte(4);
        String strHex = new BigInteger(1, val).toString(16);
        return Long.parseLong(strHex, 16);
    }

    public int[] readUint16s() {
        int n = this.readUint16();
        int[] s = new int[n];
        for (int i = 0; i < n; i++) {
            s[i] = this.readUint16();
        }
        return s;
    }

    public int readUint32TInteger() {
        byte[] val = readByte(4);
        return new BigInteger(1, val).intValue();
    }

    public float readUint64TFloat() {
        byte[] val = readByte(8);
        return new BigInteger(1, val).floatValue();
    }

    public long readUint64TLong() {
        byte[] val = readByte(8);
        return new BigInteger(1, val).longValue();
    }

    public double readUint64TDouble() {
        byte[] val = readByte(8);
        return new BigInteger(1, val).doubleValue();
    }


    public byte[] readByte(int length) {
        byte[] copy = new byte[length];
        System.arraycopy(data, cursorIndex, copy, 0, length);
        cursorIndex += length;
        return copy;
    }

    private int byte2int(byte[] val) {
        String strHex = new BigInteger(1, val).toString(16);
        return Integer.parseInt(strHex, 16);
    }

}
